""" 化妆品 """
import pandas as pd
import time
import pyautogui
import random

from DrissionPage import ChromiumPage, ChromiumOptions
from DrissionPage.errors import ContextLostError, ElementNotFoundError

co = ChromiumOptions().set_paths(browser_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") # 设置浏览器路径
co.set_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.2365.52')  # 设置 User-Agent
page = ChromiumPage(co)

# 拿到所有商品链接和商品名称
page.get('https://www.otto.de/technik/unterhaltungselektronik/')

def mouse_down():
    # 获取屏幕中心坐标
    screen_width, screen_height = pyautogui.size()
    start_x, start_y = screen_width // 2, screen_height // 2
    end_y = start_y + 100  # 向下移动 100 像素

    # 移动鼠标到屏幕中心
    pyautogui.moveTo(start_x, start_y, duration=0.2)

    # 按住鼠标右键
    pyautogui.mouseDown(button='right')

    # 生成滑动轨迹（向下 + 随机 X 抖动）
    steps = random.randint(5, 10)  # 步数越多越平滑
    for i in range(steps):
        curr_x = start_x + random.randint(-2, 2)  # X 抖动
        curr_y = start_y + ((i + 1) / steps) * 100  # Y 方向逐步增加
        pyautogui.moveTo(curr_x, curr_y, duration=random.uniform(0.05, 0.1))

    # 释放鼠标右键
    pyautogui.mouseUp(button='right')

for i in range(37):
    mouse_down()
    time.sleep(0.5)

links = page.eles('x://article[contains(@class, "product")]')

product_list = []
for link in links:
    try:
        price_and_freight = link.ele('x:.//div[@class="find_tile__priceContainer"]').text

        price = price_and_freight.split('\n')[0]
        if len(price_and_freight.split('\n')) !=1:
            freight = price_and_freight.split('\n')[1]
        else:
            freight = None

        print(f"价格: {price}")
        print(f"运费: {freight}")
    except ElementNotFoundError:
        print("找不到价格和运费信息，跳过")
        continue


    try:
        brand_ele = link.ele('x:.//span[@class="find_tile__brandInName"]')
        brand = brand_ele.text
        # 拿到 <p> 标签的完整文本
        p_text = brand_ele.parent().text
        product_name = p_text.replace(brand, '').strip()
    except ElementNotFoundError:
        print("找不到品牌和商品名，跳过")
        continue

    print(f"品牌: {brand}")
    print(f"商品名: {product_name}")

    try:
        a_tag = link.ele('x:.//a[contains(@href, "/p/")]')  # 更宽松
    except ElementNotFoundError:
        print("找不到链接元素，跳过")
        continue
    if a_tag:
        href = a_tag.attr('href')
        print(f"链接: {href}")
    else:
        href = None
        print("找不到链接元素，跳过")
    try:
        source_tag = link.ele('x:.//picture/source')
    except ElementNotFoundError:
        print("找不到图片的 <source> 标签")
        continue

    if source_tag:
        img_url = source_tag.attr('srcset')
        print(f"图片链接: {img_url}")
    else:
        img_url = None
        print("找不到图片的 <source> 标签")
    try:
        comment = link.ele('x://span[@class="reptile_tile__rating__number"]').text
        comment = comment.replace('(', '').replace(')', '').strip()
        print(f"评论数: {comment}")
    except ElementNotFoundError:
        print("评论信息缺失，跳过")
        comment = None
        continue

    product_dict = {
        'brand': brand,
        'product_name': product_name,
        'href': href,
        'img_url': img_url,
        'comment': comment,
        'price': price,
        'freight': freight,
    }
    product_list.append(product_dict)
    print(len(product_list))
    time.sleep(0.5)

page.close()
# 保存为 excel
try:
    df = pd.DataFrame(product_list)
    df.to_excel('otto_makeup_2.xlsx', index=False)
except ImportError:
    print("未安装 pandas，无法保存为 Excel")

print('over')

